/**
 * @description 定义路由拦截器
 */

 import { JOIN, LOGIN_FLAG } from "@/config/common.conf"
 import store from "@/store"
 import { deCodeApi } from "@/utils"
 
 const interceptor = function(to,_,next){
     if(to.meta.nologin){
         next()
         return
     }
     //判断是否有登录标识
     let loginFlag = sessionStorage.getItem(LOGIN_FLAG)
     if(!loginFlag){
         next('/login')
         return
     }
     //因为解密、切割可能会出错--所以用捕获异常来写
     try{
         let str = deCodeApi(loginFlag).split(JOIN)
         //校验token时效性
         let time = 30 * 60 * 60 * 1000
         let passtime = Date.now() - str[1] - time > 0
         if(passtime){
             //如果过期，就清除缓存，并跳转到登录页面
             sessionStorage.removeItem(LOGIN_FLAG)
             next('/login')
             console.log('登录超时')
         }
         //校验token正确性和安全性
         const token = store.getters['common/token']
         if(str[0] === token){
             next()
         }else{
             sessionStorage.removeItem(LOGIN_FLAG)
             next('/login')
             console.log('登录标识有误')
         }
     }catch(e){
         sessionStorage.removeItem(LOGIN_FLAG)
         next('/login')
         console.log(e + '------------登录标识异常，请检查')
     }
 }

 export default interceptor